package com.niodata.dp.web.security;

import com.niodata.dp.core.usermgr.model.UserInfo;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class ContextUtil {

  private static final ConcurrentMap<Long, DpContext> cache = new ConcurrentHashMap<>();

  private static DpUserDetails getCurrentUserDetails() {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context == null) {
      return null;
    }
    if (context.getAuthentication() == null) {
      return null;
    }
    Object principal = context.getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
      return (DpUserDetails) principal;
    }
    return null;
  }

  public static UserInfo getCurrentUser() {
    DpUserDetails details = getCurrentUserDetails();
    if (details != null) {
      return details.getUserInfo();
    }
    return null;
  }

  /**
   * 当前context.
   *
   * @return DpContext
   */
  public static DpContext currentContext() {
    DpUserDetails details = getCurrentUserDetails();
    if (details != null) {
      DpContext context = cache.get(details.getUserInfo().getUserId());

      if (context == null) {
        synchronized (cache) {
          context = cache.get(details.getUserInfo().getUserId());
          if (context == null) {
            synchronized (ContextUtil.class) {
              context = new DpContext();
              context.set(details);
              cache.put(details.getUserInfo().getUserId(), context);
            }
          }
        }
      }

      return context;
    }
    return null;
  }

}
